<template>
  <div class="app-views" v-loading="loading">
    <div class="item-box" v-loading="loading" style="border-right: 1px dashed #e6e6e6">
      <div class="sub-title">
        <i class="iconfont icon-list" style="margin-right: 5px; font-weight: bold"></i>
        <div class="Title">设备列表</div>
      </div>
      <div class="device-list">
        <DCard :dName="item.name" :isCheck="isCheckCard == item.value" @click.native="handlerisCheck(item)"
          v-for="(item, index) in cat" :key="index" :status="deviceList[index]" :use="isUse[index]" />
      </div>
    </div>
    <div class="device-views">
      <div class="sub-title">
        <i class="iconfont icon-shebeituceng-" style="margin-right: 5px"></i>
        <div class="Title">设备图</div>
      </div>
      <div class="device-img">
        <div class="device-img-rec">
          <div class="img-box">
            <img src="@/assets/images/cat.png" alt="" />
          </div>
          <div class="deviceStatus">
            <div class="title">
              设备状态

              <i class="el-icon-edit" @click="openParamSet" v-hasPermi="['assembly:device:edit']"></i>
              <i class="iconfont icon-guzhangjiance" @click="handlerErrorCheck"></i>
            </div>
            <div class="list" v-loading="showDeviceStatus.length == 0">
              <div class="item" v-for="item in showDeviceStatus" :key="item.id">
                <div class="descript">
                  <span class="note"> {{ item.note }}</span>
                  <span class="value">
                    {{ item.message }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="signal">
          <div class="sub-title">
            <i class="iconfont icon-PLCxinhaoganzhizhongduan" style="margin-right: 5px"></i>
            <div class="Title">信号列表</div>
          </div>
          <div class="signal-table">
            <el-table :data="tableData" style="width: 100%" height="100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="cmd" label="指令内容" width="200" show-overflow-tooltip />
              <el-table-column prop="cmdType" label="命今类型" show-overflow-tooltip />
              <el-table-column prop="createTime" label="时间" width="150">
                <template slot-scope="scope">
                  {{ scope.row.createTime.substr(10) }}
                </template>
              </el-table-column>
              <el-table-column label="完成状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.state | tagType">{{
                    scope.row.state | status
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                  <el-button icon="el-icon-close" type="text" v-if="!scope.row.state"
                    v-hasPermi="['assembly:device:edit']"
                    @click="handlerCmd('fallbackAction', scope.row)">取消</el-button>
                  <el-button icon="el-icon-check" type="text" v-hasPermi="['assembly:device:edit']"
                    v-if="!scope.row.state" @click="handlerCmd('executionCompleted', scope.row)">完成</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <div class="item-box">
      <LogView :jobGroup="5" :isShow="isShow" />
    </div>
    <el-drawer title="设备参数" :visible.sync="drawer" :direction="direction">
      <div class="params" v-if="deviceParams != null" v-loading="loadDeviceParam">
        <div class="param_item_W">
          <div class="paramsName">小车是否使用</div>
          <div class="paramView">

            <el-radio-group v-model="deviceParams.object.use">
              <el-radio :label="true">开启</el-radio>
              <el-radio :label="false">关闭</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="param_item_W">
          <div class="paramsName">是否开启小车A槽</div>
          <div class="paramView">
            <el-radio-group v-model="deviceParams.object.layer1">
              <el-radio :label="true">开启</el-radio>
              <el-radio :label="false">关闭</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="param_item_W">
          <div class="paramsName">是否开启小车B槽</div>
          <div class="paramView">
            <el-radio-group v-model="deviceParams.object.layer2">
              <el-radio :label="true">开启</el-radio>
              <el-radio :label="false">关闭</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="param_item_W">
          <div class="paramsName">接收台子</div>
          <div class="paramView">
            <el-checkbox-group v-model="deviceParams.object.allowPlace">
              <el-checkbox label="1101" :disabled="isDisable">一线</el-checkbox>
              <el-checkbox label="1104" :disabled="isDisable">二线</el-checkbox>
              <el-checkbox label="1145" :disabled="isDisable">三线</el-checkbox>
              <el-checkbox label="1110" :disabled="isDisable">四线</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="param_item_W">
          <div class="paramsName">输送台子</div>
          <div class="paramView">
            <el-checkbox-group v-model="deviceParams.object.glassTemperingFurnaceIds">
              <el-checkbox :label="1" :disabled="!isDisableA27">A27</el-checkbox>
              <el-checkbox :label="2" :disabled="!isDisable">索奥斯线</el-checkbox>
              <el-checkbox :label="3" :disabled="!isDisableGLST">格拉斯通线</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="param_item_W">
          <div class="paramsName">当前输送台</div>
          <div class="paramView">
            <el-radio-group v-model="deviceParams.object.currentFurId">
              <el-radio :label="1" :disabled="!isDisableA27">A27</el-radio>
              <el-radio :label="2" :disabled="!isDisable">索奥斯线</el-radio>
              <el-radio :label="3" :disabled="!isDisableGLST">格拉斯通线</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="param_item_W">
          <div class="paramsName">安全位置</div>
          <div class="paramView">
            <span v-show="SafeLocation" @click.stop="handlerSpace('SafeLocation')">{{ deviceParams.object.safeLocation
              }}</span>
            <el-input-number v-show="!SafeLocation" size="mini" ref="SafeLocation"
              v-model="deviceParams.object.safeLocation" @blur="handlerSpace('SafeLocation')"></el-input-number>
          </div>
        </div>
        <div class="param_item_W">
          <div class="paramsName">小车总宽度</div>
          <div class="paramView">
            <span v-show="Width" @click.stop="handlerSpace('Width')">{{
              deviceParams.object.width
            }}</span>
            <el-input-number v-show="!Width" size="mini" ref="Width" v-model="deviceParams.object.width"
              @blur="handlerSpace('Width')"></el-input-number>
          </div>
        </div>
        <div class="param_item_W gridBox">
          <div class="paramsName gridHeader">
            <div>使用格号</div>
            <div style="display: flex; align-items: center; margin-left: auto">
              <div style="
                  width: 10px;
                  height: 10px;
                  background-color: #409eff;
                  margin-right: 3px;
                "></div>
              使用
            </div>
            <div style="display: flex; align-items: center; margin-left: 5px">
              <div style="
                  width: 10px;
                  height: 10px;
                  background-color: #a6a9ad;
                  margin-right: 3px;
                "></div>
              禁用
            </div>
          </div>
          <div class="checkBoxGroup">
            <el-checkbox-group v-model="checkList">
              <el-checkbox v-if="isCheckCard == 0 || isCheckCard == 2" :indeterminate="checkFillArrayExit(50, deviceParams.object.canUseList) != 0 &&
                checkFillArrayExit(50, deviceParams.object.canUseList) != 50
                " :label="50">1-50</el-checkbox>
              <el-checkbox :indeterminate="checkFillArrayExit(100, deviceParams.object.canUseList) !=
                0 &&
                checkFillArrayExit(100, deviceParams.object.canUseList) != 50
                " :label="100">51-100</el-checkbox>
              <el-checkbox :indeterminate="checkFillArrayExit(150, deviceParams.object.canUseList) !=
                0 &&
                checkFillArrayExit(150, deviceParams.object.canUseList) != 50
                " :label="150">101-150</el-checkbox>
              <el-checkbox :indeterminate="checkFillArrayExit(200, deviceParams.object.canUseList) !=
                0 &&
                checkFillArrayExit(200, deviceParams.object.canUseList) != 50
                " :label="200">151-200</el-checkbox>
              <el-checkbox :indeterminate="checkFillArrayExit(250, deviceParams.object.canUseList) !=
                0 &&
                checkFillArrayExit(250, deviceParams.object.canUseList) != 50
                " :label="250">201-250</el-checkbox>
              <el-checkbox :indeterminate="checkFillArrayExit(300, deviceParams.object.canUseList) !=
                0 &&
                checkFillArrayExit(300, deviceParams.object.canUseList) != 50
                " :label="300">251-300</el-checkbox>
              <el-checkbox v-if="isCheckCard == 1 || isCheckCard == 3" :indeterminate="checkFillArrayExit(300, deviceParams.object.canUseList) !=
                0 &&
                checkFillArrayExit(300, deviceParams.object.canUseList) != 50
                " :label="350">301-350</el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="paramView">
            <div class="grid" v-for="item in gridRange[isCheckCard]" :key="item" :class="deviceParams.object.canUseList.includes(item)
              ? 'gridActive'
              : ''
              " @click="handlerCheckGrid(item)">
              {{ item }}
            </div>
          </div>
        </div>
        <div class="footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handlerEditDevice('deviceParams')">确定</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog :title="cat[isCheckCard].name" :visible.sync="dialogCatLog" width="65%">
      <CatLog :tableData="logData" />
    </el-dialog>
  </div>
</template>

<script>
import DCard from "@/views/components/production/dCard.vue";
import LogView from "@/views/components/production/logViews.vue";
import { cat, underCat } from "../Config/label";
import mixin from "../mixin/index";
import { catDB } from "@/config/db";
import { mapState } from "vuex";
import { deviceEditParam } from "@/api/assembly/device";
import { getTransportCheckList } from "@/api/assembly/cage"
import CatLog from '@/views/components/production/catLog.vue';
import {
  comparabelArray,
  checkFillArrayExit,
  intervalNumber,
} from "@/utils/index";

export default {
  components: {
    DCard,
    LogView,
    CatLog
  },
  props: {},
  mixins: [mixin],
  data() {
    return {
      underCat,
      cat,
      isCheckCard: 0,
      loading: false,
      isShow: false,
      tableData: [],
      device: null,
      drawer: false,
      drawerCat: false,
      deviceParams: null,
      underCatParams: null,
      direction: "rtl",
      loadDeviceParam: true,
      SafeLocation: true,
      Width: true,
      selectCat: 0,
      isUse: [216, 272, 328, 384],
      checkList: [],
      dialogCatLog: false,
      logData: {}
    };
  },
  watch: {
    checkList(newValue, oldValue) {
      const arr = comparabelArray(oldValue, newValue);
      const isIncrease = oldValue.length > newValue.length ? false : true;

      if (isIncrease) {
        for (let i = arr[0]; i > arr[0] - 50; i--) {
          if (!this.deviceParams.object.canUseList.includes(i)) {
            this.deviceParams.object.canUseList.push(i);
          }
        }
      } else {
        for (let i = arr[0]; i > arr[0] - 50; i--) {
          let indexOf = this.deviceParams.object.canUseList.indexOf(i);
          indexOf != -1
            ? this.deviceParams.object.canUseList.splice(indexOf, 1)
            : null;
        }
      }
    },
  },
  methods: {
    async handlerErrorCheck() {
      await this.initData()
      this.deviceParams.object.errorCheck = true
      deviceEditParam(this.deviceParams).then((res) => {
        res.code != 200 ? this.$message(res.msg || "网络异常,请稍后再试!") : ''
      });
      const loading = this.$loading({
        lock: true,
        text: '正在获取小车信息,请稍候!',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        getTransportCheckList({ transportCheckId: this.isCheckCard + 1 }).then((res) => {
          this.logData = res.data
        })
        loading.close()
        this.dialogCatLog = true
      }, 5000)



    },
    checkFillArrayExit,
    handlerCheckGrid(item) {
      let canUseList = this.deviceParams.object.canUseList;
      let indexOf = canUseList.indexOf(item);
      indexOf == -1 ? canUseList.push(item) : canUseList.splice(indexOf, 1);
      this.handlerCheckisValue(item);
    },
    handlerCheckisValue(item) {
      let canUseList = this.deviceParams.object.canUseList;
      let num = intervalNumber(item);
      let total = checkFillArrayExit(num, canUseList);
      if (total == 50) {
        this.checkList.push(num);
      }
      if (total == 0) {
        let indexOf = this.checkList.indexOf(num);
        indexOf != -1 && this.checkList.splice(this.checkList.indexOf(num), 1);
      }
    },
    handlerSelect(e) {
      this.selectCat = e;
      this.underCatParams =
        this.deviceParamsList.length == 0
          ? null
          : this.deviceParamsList[this.selectCat];
    },
    handlerSpace(e) {
      this[e] = !this[e];
      this.$nextTick(() => {
        !this[e] && this.$refs[e].focus();
      });
    },
    handlerEditDevice(e) {
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^5563$/,
        inputErrorMessage: "密码错误",
        inputType: "password",
      })
        .then(({ value }) => {
          deviceEditParam(this[e]).then((res) => {
            if (res.code == 200) {
              this.$message.success("修改设备状态成功");
              this.drawer = false;
              this.drawerCat = false;
              this.initData();
            } else {
              this.$message.error("修改设备状态失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    // index 选中的card
    handlerisCheck(item) {
      this.isCheckCard = item.value;
      this.device = item;
      this.checkList = []
      this.getDeviceSignal();
    },
    async openParamSet() {
      this.drawer = true;
      this.initData();
    },
    async initData() {
      this.loadDeviceParam = true;
      let paramList = this.cat.map((item) => {
        return {
          name: item.deviceType,
          id: item.id,
        };
      });
      await this.$store.dispatch("getDeviceMap", paramList);

      this.deviceParams =
        this.deviceParamsList.length == 0
          ? null
          : this.deviceParamsList[this.isCheckCard];
      this.handlerInitCheckBox();
      this.loadDeviceParam = false;
    },
    handlerInitCheckBox() {
      let a = [50, 100, 150, 200, 250, 300, 350, 400];
      a.forEach((item) => {
        this.handlerCheckisValue(item);
      });
    },
  },
  created() {
    this.device = cat[this.isCheckCard];
    this.getSignal(catDB);
  },
  destroyed() { },
  computed: {
    ...mapState({
      deviceParamsList: (state) => state.deviceStatus.deviceParams,
    }),
    showDeviceStatus() {
      if (this.deviceList.length == 0) return [];
      let blockAddr = [
        [216, 218, 248],
        [272, 274, 304],
        [328, 330, 360],
        [384, 386, 416],
      ];
      return this.deviceList[this.isCheckCard].plcSignals.filter((item) =>
        blockAddr[this.isCheckCard].includes(item.addr)
      );
    },
    isDisable() {
      if (this.isCheckCard == 2 || this.isCheckCard == 3) return true;
      return false;
    },
    isDisableA27() {
      if (this.isCheckCard == 2) return true;
      return false;
    },
    isDisableGLST() {
      if (this.isCheckCard == 3) return true;
      return false;
    },
    gridRange() {
      let gridArr = [[], [], [], []];
      let map = {
        0: [1, 300],
        1: [51, 350],
        2: [1, 300],
        3: [51, 350],
      };
      for (let key in map) {
        for (let i = map[key][0]; i <= map[key][1]; i++) {
          gridArr[key].push(i);
        }
      }
      return gridArr;
    },
  },
  filters: {
    devicePlcStatus(arg) {
      let arr = ["circle-stop", "circle-forbid", "circle-active"];
      let a = [216, 272, 328, 384];
      let b = [218, 274, 330, 386];
      let c = [248, 304, 360, 416];
      if (a.includes(arg.addr)) {
        if (arg.message * 1 == 1) return arr[2];
      }
      if (b.includes(arg.addr)) {
        if (arg.message * 1 == 0) return arr[1];
      }
      if (c.includes(arg.addr)) {
        if (arg.message * 1 == 0) return arr[0];
        if (arg.message * 1 == 1) return arr[1];
        if (arg.message * 1 == 2) return arr[2];
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../style/index.less");

/deep/.el-dialog__body {
  padding-top: 0 !important;
}

/deep/ .el-checkbox {
  margin-right: 15px;
}

img {
  width: 50%;
  height: 98%;
}

.param_item_W {
  display: flex;
  flex-direction: row;
}

.select {
  min-height: 40px;
  display: flex;
  box-shadow: 3px 3px 3px rgba(0, 0, 0, 5%);
  cursor: pointer;

  .underCat {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    font-weight: bold;
  }

  .active {
    background: linear-gradient(#fafafa, #1890ff);
  }
}

.params {
  display: flex;
  flex-direction: column;
  height: 100%;

  .paramsName {
    min-height: 30px;
    padding: 0px 10px;
    display: flex;
    font-size: 16px;
    align-items: center;
  }

  .paramView {
    min-height: 40px;
    max-width: 100%;
    display: flex;
    align-items: center;
    padding: 0px 0px 0px 10px !important;
    margin-left: auto;
    flex-wrap: wrap;

    span {
      cursor: pointer;
    }

    .grid {
      width: 5.15%;
      height: 30px;
      background-color: #a6a9ad;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 5px;
      margin-right: 4px;
      cursor: pointer;
      font-size: 14px;
    }

    .gridActive {
      background-color: #409eff;
    }
  }

  .gridBox {
    flex-direction: column;
  }

  .gridHeader {
    display: flex;
    flex-wrap: wrap;
  }

  .checkBoxGroup {
    padding: 0px 10px;
    display: flex;
  }
}
</style>
